package com.itcast.tanhuaserver.interceptor;

import com.itcast.tanhuaserver.domain.User;
import com.itcast.tanhuaserver.domain.UserThreadLocal;
import com.itcast.tanhuaserver.service.UserService;
import com.itcast.tanhuaserver.utils.NoAuthorization;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.ws.handler.Handler;

/**
 * @PachageName: com.itcast.tanhuaserver.interceptor
 * @ClassName:
 * @Description: TODO
 * @Author: Hushi
 * @DateTime: 2021/2/1718:05
 * @Version 1.0
 */
@Component
public class TokenInterceptor implements HandlerInterceptor {
    @Autowired
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println(request.getRequestURL());
        System.out.println(request.getRequestURI());
        if (handler instanceof HandlerMethod){

            HandlerMethod handlerMethod = (HandlerMethod) handler;
            NoAuthorization annotation = handlerMethod.getMethod().getAnnotation(NoAuthorization.class);
            //若访问方法上标记该注解,则不用判断token
            if (annotation != null){
                return true;
            }
        }

        //判断token是否失效,不失效则保存在ThreadLocal中
        String token = request.getHeader("Authorization");
        if (StringUtils.isNotEmpty(token)){
            User user = this.userService.queryUserByToken(token);
            if (user != null){
                UserThreadLocal.set(user);
                return true;
            }
        }

        //token失效或非法,返回无权限
        response.setStatus(401); //无权限访问
        return false;
    }
}
